﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Common.Utilities;
using ZedGraph;

namespace Workflows.Components.Entities.MasterData
{
    public partial class TableFieldProfileViewer : Form
    {
        public TableFieldProfileViewer()
        {
            InitializeComponent();
        }

        private void TableFieldProfileViewer_Load(object sender, EventArgs e)
        {

        }

        private void PopulateTreeView(string profileFilePath)
        {
            this.tree_Fields.Nodes.Clear();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(profileFilePath);
            XmlNode root = xDoc.DocumentElement;
            XmlNodeList schemaNodes = root.SelectNodes("Schema");
            if(schemaNodes !=null && schemaNodes.Count>0)
            {
                foreach(XmlNode schemaNode in schemaNodes)
                {
                    string schemaName = XmlDataUtil.GetAttributeValue(schemaNode, "SchemaName", "");
                    TreeNode schemaTn=new TreeNode(schemaName);
                    schemaTn.ImageIndex = schemaTn.SelectedImageIndex = 0;
                    this.tree_Fields.Nodes.Add(schemaTn);
                    foreach(XmlNode tblNode in schemaNode.ChildNodes)
                    {
                        string tblName = XmlDataUtil.GetAttributeValue(tblNode, "TableName", "");
                        TreeNode tblTn=new TreeNode(tblName);
                        tblTn.ImageIndex = tblTn.SelectedImageIndex = 1;
                        schemaTn.Nodes.Add(tblTn);

                        foreach (XmlNode statNode in tblNode.ChildNodes)
                        {
                            FieldStat fieldStat = new FieldStat();
                            fieldStat.FieldName = XmlDataUtil.GetAttributeValue(statNode, "FieldName", "");
                            fieldStat.DataType =
                                (SimpleDataType) Enum.Parse(
                                                     typeof (SimpleDataType),
                                                     XmlDataUtil.GetAttributeValue(
                                                         statNode,
                                                         "DataType",
                                                         SimpleDataType.StringListType.ToString()));
                            fieldStat.Count = int.Parse(XmlDataUtil.GetAttributeValue(statNode, "Count", "0"));
                            fieldStat.DistinctValueCount =
                                int.Parse(XmlDataUtil.GetAttributeValue(statNode, "DistinctCount", "0"));
                            fieldStat.MissingValueCount =
                                int.Parse(XmlDataUtil.GetAttributeValue(statNode, "NullCount", "0"));
                            fieldStat.MaxValue = SimpleDataTypeUtil.ToDbValue(fieldStat.DataType,
                                                                              XmlDataUtil.GetAttributeValue(
                                                                                  statNode, "Max", ""));
                            fieldStat.MinValue = SimpleDataTypeUtil.ToDbValue(fieldStat.DataType,
                                                                              XmlDataUtil.GetAttributeValue(
                                                                                  statNode, "Min", ""));
                            fieldStat.Average = SimpleDataTypeUtil.ToDbValue(fieldStat.DataType,
                                                                             XmlDataUtil.GetAttributeValue(
                                                                                 statNode, "Mean", ""));
                            fieldStat.Mode = SimpleDataTypeUtil.ToDbValue(fieldStat.DataType,
                                                                          XmlDataUtil.GetAttributeValue(
                                                                              statNode, "Mode", ""));
                            fieldStat.SD = SimpleDataTypeUtil.ToDbValue(
                                fieldStat.DataType,
                                XmlDataUtil.GetAttributeValue(statNode, "SD", ""));
                            fieldStat.Distributions = new Dictionary<object, int>();
                            XmlNodeList nomNodes = statNode.SelectNodes("NominalValue");
                            if(nomNodes !=null && nomNodes.Count>0)
                            {
                                foreach(XmlNode nomNode in nomNodes)
                                {
                                    string value = XmlDataUtil.GetAttributeValue(nomNode, "Value", "");
                                    int freq = int.Parse(XmlDataUtil.GetAttributeValue(nomNode, "Frequency", "0"));
                                    fieldStat.Distributions.Add(value, freq);
                                }
                            }
                            
                            TreeNode fieldTn = new TreeNode(fieldStat.FieldName);
                            fieldTn.Tag = fieldStat;
                            fieldTn.ImageIndex = fieldTn.SelectedImageIndex = 2;
                            tblTn.Nodes.Add(fieldTn);
                        }

                    }
                }
            }
        }

        private void btn_BrowseProfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg=new OpenFileDialog();
            dlg.Filter = "Profile files(*.prof)|*.prof|Excel files(*.xlsx)|*.xlsx|All files(*.*)|*.*";
            if(dlg.ShowDialog()==DialogResult.OK)
            {
                this.txt_ProfileFile.Text = dlg.FileName;
                this.PopulateTreeView(dlg.FileName);
            }
        }
        
        private void tree_Fields_MouseUp(object sender, MouseEventArgs e)
        {
            this.tree_Fields.SelectedNode =
                this.tree_Fields.GetNodeAt(e.X, e.Y);
            if(this.tree_Fields.SelectedNode !=null)
            {
                if (this.tree_Fields.SelectedNode.ImageIndex == 1)
                {
                    // display field stats in table
                    List<FieldStat> fieldStats=new List<FieldStat>();
                    if (this.tree_Fields.SelectedNode.Nodes != null && this.tree_Fields.SelectedNode.Nodes.Count > 0)
                    {
                        foreach (TreeNode fieldTn in this.tree_Fields.SelectedNode.Nodes)
                        {
                            FieldStat fieldStat = (FieldStat)fieldTn.Tag;
                            fieldStats.Add(fieldStat);
                        }
                    }
                    this.dv_TableStats.DataSource = fieldStats;
                    this.dv_TableStats.BringToFront();
                }
                else if(this.tree_Fields.SelectedNode.ImageIndex==2)
                {
                    // display dependency 
                    FieldStat fieldStat = (FieldStat) this.tree_Fields.SelectedNode.Tag;
                    if (fieldStat.Distributions != null && fieldStat.Distributions.Count > 0)
                    {
                        this.zedGraph.BringToFront();
                        this.DisplayFieldDistribution(fieldStat.FieldName, fieldStat.Distributions);
                    }
                    else
                    {
                        this.ClearFieldDistributionChart();
                    }
                }
            }
        }

        private void DisplayFieldDistribution(string fieldName, Dictionary<object, int> distributions)
        {
            GraphPane myPane = this.zedGraph.GraphPane;
            myPane.CurveList.Clear();
            myPane.GraphObjList.Clear();
            // Set the title and axis labels
            myPane.Title.Text = string.Format("{0} distribution", fieldName);
            myPane.XAxis.Title.Text = fieldName;
            myPane.YAxis.Title.Text = "Frequency";

            double[] yVals=new double[distributions.Count];
            string[] xLabels=new string[distributions.Count];
            // Generate random data for three curves
            int i = 0;
            double maxY = 0;
            foreach(object xVal in distributions.Keys)
            {
                xLabels[i] = xVal.ToString();
                yVals[i] = distributions[xVal];
                if (distributions[xVal] > maxY)
                    maxY = distributions[xVal];
                i++;
            }

            // create the curves
            BarItem myCurve = myPane.AddBar("Frequency", null, yVals, Color.Blue);

            // set x labels
            myPane.XAxis.MajorTic.IsBetweenLabels = true;
            myPane.XAxis.Scale.TextLabels = xLabels;
            myPane.XAxis.Type = AxisType.Text;

            // Fill the axis background with a color gradient
            myPane.Chart.Fill = new Fill(Color.White,
               Color.FromArgb(255, 255, 166), 45.0F);

            this.zedGraph.AxisChange();

            // expand the range of the Y axis slightly to accommodate the labels
            myPane.YAxis.Scale.Max = maxY + myPane.YAxis.Scale.MajorStep;

            // Create TextObj's to provide labels for each bar
            BarItem.CreateBarLabels(myPane, false, "f0");

            this.zedGraph.Update();
            this.zedGraph.Refresh();
        }

        private void ClearFieldDistributionChart()
        {
            GraphPane myPane = this.zedGraph.GraphPane;
            myPane.CurveList.Clear();
            myPane.GraphObjList.Clear();
            this.zedGraph.Update();
            this.zedGraph.Refresh();
        }
    }
}
